import tkinter as tk
from tkinter import messagebox

class Reversi:
    def __init__(self, master):
        self.master = master
        self.master.title('黑白棋')
        self.board_size = 8  # 标准8x8棋盘
        self.cell_size = 60  # 每个格子的大小
        self.margin = 20     # 边距
        
        # 棋盘状态：0表示空，1表示黑棋，2表示白棋
        self.board = [[0 for _ in range(self.board_size)] for _ in range(self.board_size)]
        self.current_player = 1  # 1是黑棋，2是白棋
        self.game_over = False
        self.valid_moves = set()  # 初始化valid_moves
        
        # 初始化棋盘中心的四个棋子
        center = self.board_size // 2
        self.board[center-1][center-1] = 2  # 白
        self.board[center-1][center] = 1    # 黑
        self.board[center][center-1] = 1    # 黑
        self.board[center][center] = 2      # 白
        
        self.setup_ui()
        self.update_valid_moves()  # 更新有效移动位置
        
    def setup_ui(self):
        # 创建画布
        canvas_size = self.board_size * self.cell_size + 2 * self.margin
        self.canvas = tk.Canvas(self.master, width=canvas_size, height=canvas_size, bg='#228B22')
        self.canvas.pack(side=tk.LEFT)
        
        # 创建信息面板
        info_panel = tk.Frame(self.master)
        info_panel.pack(side=tk.RIGHT, padx=20)
        
        self.status_var = tk.StringVar()
        self.status_label = tk.Label(info_panel, textvariable=self.status_var, font=('Arial', 12))
        self.status_label.pack(pady=5)
        
        self.score_var = tk.StringVar()
        self.score_label = tk.Label(info_panel, textvariable=self.score_var, font=('Arial', 12))
        self.score_label.pack(pady=5)
        
        # 绘制棋盘
        self.draw_board()
        
        # 绑定鼠标点击事件
        self.canvas.bind('<Button-1>', self.handle_click)
        
    def draw_board(self):
        self.canvas.delete('all')
        
        # 画格子线
        for i in range(self.board_size + 1):
            # 横线
            self.canvas.create_line(
                self.margin, self.margin + i * self.cell_size,
                self.margin + self.board_size * self.cell_size,
                self.margin + i * self.cell_size,
                fill='black', width=2
            )
            # 竖线
            self.canvas.create_line(
                self.margin + i * self.cell_size, self.margin,
                self.margin + i * self.cell_size,
                self.margin + self.board_size * self.cell_size,
                fill='black', width=2
            )
        
        # 画棋子和有效移动提示
        for i in range(self.board_size):
            for j in range(self.board_size):
                x = self.margin + j * self.cell_size + self.cell_size // 2
                y = self.margin + i * self.cell_size + self.cell_size // 2
                
                if self.board[i][j] != 0:
                    # 画棋子
                    color = 'black' if self.board[i][j] == 1 else 'white'
                    self.canvas.create_oval(
                        x - self.cell_size//2 + 5,
                        y - self.cell_size//2 + 5,
                        x + self.cell_size//2 - 5,
                        y + self.cell_size//2 - 5,
                        fill=color,
                        outline='black'
                    )
                elif (i, j) in self.valid_moves:
                    # 画有效移动提示点
                    self.canvas.create_oval(
                        x - 5, y - 5, x + 5, y + 5,
                        fill='red'
                    )
        
        # 更新状态显示
        self.update_status()
        
    def update_status(self):
        black_count = sum(row.count(1) for row in self.board)
        white_count = sum(row.count(2) for row in self.board)
        
        self.score_var.set(f'黑棋：{black_count}  白棋：{white_count}')
        
        if self.game_over:
            if black_count > white_count:
                self.status_var.set('游戏结束！黑棋胜！')
            elif white_count > black_count:
                self.status_var.set('游戏结束！白棋胜！')
            else:
                self.status_var.set('游戏结束！平局！')
        else:
            self.status_var.set('当前回合：' + ('黑棋' if self.current_player == 1 else '白棋'))
        
    def handle_click(self, event):
        if self.game_over:
            return
            
        # 将点击位置转换为棋盘坐标
        col = (event.x - self.margin) // self.cell_size
        row = (event.y - self.margin) // self.cell_size
        
        if 0 <= row < self.board_size and 0 <= col < self.board_size:
            self.make_move(row, col)
            
    def make_move(self, row, col):
        if (row, col) not in self.valid_moves:
            return
            
        # 放置棋子并翻转对手的棋子
        self.board[row][col] = self.current_player
        for direction in self.get_flips(row, col):
            self.flip_direction(row, col, direction)
            
        # 切换玩家
        self.current_player = 3 - self.current_player
        
        # 更新有效移动
        self.update_valid_moves()
        
        # 如果当前玩家没有有效移动，切换到对手
        if not self.valid_moves:
            self.current_player = 3 - self.current_player
            self.update_valid_moves()
            
            # 如果对手也没有有效移动，游戏结束
            if not self.valid_moves:
                self.game_over = True
        
        # 重绘棋盘
        self.draw_board()
        
    def get_flips(self, row, col):
        """获取所有可以翻转的方向"""
        flips = []
        for dr in [-1, 0, 1]:
            for dc in [-1, 0, 1]:
                if dr == 0 and dc == 0:
                    continue
                if self.check_direction(row, col, dr, dc):
                    flips.append((dr, dc))
        return flips
        
    def check_direction(self, row, col, dr, dc):
        """检查某个方向是否可以翻转"""
        r, c = row + dr, col + dc
        if not (0 <= r < self.board_size and 0 <= c < self.board_size):
            return False
            
        if self.board[r][c] != 3 - self.current_player:
            return False
            
        while 0 <= r < self.board_size and 0 <= c < self.board_size:
            if self.board[r][c] == 0:
                return False
            if self.board[r][c] == self.current_player:
                return True
            r, c = r + dr, c + dc
            
        return False
        
    def flip_direction(self, row, col, direction):
        """翻转某个方向上的所有棋子"""
        dr, dc = direction
        r, c = row + dr, col + dc
        
        while self.board[r][c] == 3 - self.current_player:
            self.board[r][c] = self.current_player
            r, c = r + dr, c + dc
            
    def update_valid_moves(self):
        """更新当前玩家的有效移动位置"""
        self.valid_moves = set()
        for i in range(self.board_size):
            for j in range(self.board_size):
                if self.board[i][j] == 0 and self.get_flips(i, j):
                    self.valid_moves.add((i, j))

def main():
    root = tk.Tk()
    game = Reversi(root)
    root.mainloop()

if __name__ == "__main__":
    main() 